package firtest;

import utils.JDBCUtils;
import web.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class ServletDemo3 extends BaseServlet {

    public void userExactCheck(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        // 修改编码格式
//        req.setCharacterEncoding("UTF-8");		// 接受到的
//        req.setCharacterEncoding("UTF-8");
        // 数据库调用相关
        Connection connection = null;
        PreparedStatement pStatement = null;
        ResultSet rsSet = null;

        String userNum = req.getParameter("userNum");
        System.out.println();
        try {

            // 连接数据库
            connection = JDBCUtils.getConnection();
            // 创建sql语句
            String sql = "select * from student where userNum = ?";
            // 与上sql问号一一对应

            pStatement = connection.prepareStatement(sql);
            pStatement.setString( 1, userNum );



            // 申请sql语句至数据库，返回结果至resultSet
            rsSet = pStatement.executeQuery();

            // 处理结果
            if(rsSet.next())
            {
                System.out.println();
                resp.getWriter().append("true");
            }
            else {
                resp.getWriter().append("false");
//                resp.getWriter().append("接受到的");
            }
            resp.getWriter().flush();

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("数据库查询失败");
            e.printStackTrace();
            // req.setAttribute("msg", "注册失败");
        } catch (NullPointerException e) {
            // TODO: handle exception
            System.out.println("信息不完整");
//            req.setAttribute("msg", "注册失败,信息填写不完整");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, pStatement);
        }
    }
}
